<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/20
 * Time: 10:03
 */

namespace app\admin\model;


use think\Model;

use think\Exception;
class Index extends Model
{

    protected $validate          =[
        'rule'=>[
            'name'=>['require'],
            'uri' =>['require']
        ],
        'msg'=>[
            'name.require'=>'插件名称不能为空',
            'uri.require' =>'插件地址不能为空',
        ]
    ];
    protected $autoWriteTimestamp=true;
    protected $createTime         ='create_time';
    protected $updateTime         ='edit_time';

    public function addDb($data,$allow_fields,$where=[]){
        try{
            if(empty($where)){
                $count       =$this->where(function($query)use($data){
                    $query->where(['name'=>['eq',$data['name']]]);
                })->count();
                if(true==$count>0){throw new Exception('抱歉当前的插件已存在');}
                $result =$this->allowField($allow_fields)->save($data);
                if($result===false){throw new Exception($this->error);}

            }else{;
                $result         =$this->allowField($allow_fields)->isUpdate(true)->save($data);
                if(false===$result){throw new Exception($this->error);}
            }
            return $this->getLastInsID();
        }catch (Exception $exception){$this->error=$exception->getMessage();return false;}
    }

    public function lists($where,$allow_field,$order,$page){
        try{
            if(empty($order)){$order=true;}
            $list   =   $this->where($where)->order(['id'=>'DESC'])->field($allow_field)->paginate($page,false);

            $list   =   $list->toArray();
            if(empty($list)){throw new Exception('抱歉小惠没找到没有任何您需要的数据！');}
            return $list;
        }catch (Exception $exception){$this->error=$exception->getMessage();return false;}
    }
}